import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Input, Tree, Button, message } from 'antd';
import { routerRedux } from 'dva/router';
import styles from "./index.less";
const FormItem = Form.Item;
const { TreeNode } = Tree;

@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['amendantRecord/fetch'],
}))



class addShore extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeList: [],
      value: '',
      checkedKeys: null,
      open: [],
      checkButton:true
    };
  }


  // eslint-disable-next-line react/sort-comp
  fetch = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeBaseSharing/fetchc',
        payload: { robotId: currentUser.robotId },
        callback: res => {

          let temp = res
          temp.map((item, index) => item['key'] = index)
          this.setState({ treeList: temp })
        },
      });
    });
  }

  componentWillMount() {
    this.fetch()
  }


  onCheck = (checkedKeys, info) => {

    this.setState({ checkedKeys: checkedKeys })
  }

  onChange = e => {

    this.setState({ value: e.target.value })
  }

  renderTreeNodes(data) {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.text} key={item.id}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.text} key={item.id}></TreeNode>;
    });
  }

  goBack = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/knowledge/knowledgeBaseSharing'));
  }

  check = () => {

    this.setState({ open: [],checkButton:!this.state.checkButton }, () => {
      this.openedTreeNodes(this.state.treeList)
    })
  }

  openedTreeNodes(data) {
    return data.map((item) => {
      let a = this.state.open
      if (item.children) {
        this.openedTreeNodes(item.children)
      }
      a.push(item.id)
      this.setState({ open: a,checkedKeys:a }, () => {
        //
      })
    });
  }

  checks = () => {

    this.setState({ open: [],checkedKeys:[],checkButton:!this.state.checkButton }, () => {
      // this.openedTreeNodes(this.state.treeList)
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        xs: 24,
        sm: 4,
        md: 3
      },
      wrapperCol: {
        xs: 24,
        sm: 20,
        md: 21
      }
    }
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, }} xs={24}>
                <div className={styles.title}>
                  <FormattedMessage
                    id="app.knowledgeBaseSharing.addShore"
                  />
                </div>
              </Col>
            </Row>
            <Card
              bordered={false}
            >
              <Form layout="horizontal">
                <FormItem label='共享给' {...FormItemLayont}>
                  <Input style={{ width: 250 }} onChange={this.onChange} placeholder="被共享者的登录账号" />
                </FormItem>

                <FormItem label='共享分类' {...FormItemLayont}>
                {this.state.checkButton?<Button size='small' onClick={this.check}>全选</Button>:<Button size='small' onClick={this.checks}>撤销</Button>}
                  {this.state.treeList.length === 0 ? null :<Tree
                    defaultExpandAll
                    showLine
                    checkable
                    checkedKeys={this.state.checkedKeys}
                    onCheck={this.onCheck}
                  >
                    {this.renderTreeNodes(this.state.treeList)}
                  </Tree>}
                  <div><span style={{ marginRight: 10 }}><Button onClick={this.save}>保存</Button></span><Button onClick={this.goBack}>返回</Button></div>

                </FormItem>
              </Form>
            </Card>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }

  save = () => {

    if (this.state.value === '') {
      message['error'](`被共享者的登录账号不能为空`)
    } else {
      if (this.state.checkedKeys === null || this.state.checkedKeys === '' || this.state.checkedKeys.length === 0) {
        message['error'](`共享分类不能为空`)
      } else {
        const { dispatch } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'knowledgeBaseSharing/fetchb',
            payload: { shareToUser: this.state.value, categoriesIds: this.state.checkedKeys },
            callback: res => {

              if (res.status === false) {
                // message['error'](`${res.msg}`)
              } else {
                message['success'](`${res.msg}`)
                setTimeout(() => {
                  dispatch(routerRedux.push('/knowledge/knowledgeBaseSharing'));
                }, 1000)

              }
            },
          });
        });
      }
    }
  }
}

export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(addShore));
